<template>
  <view
    class="custom-preview"
    v-if="visible"
    @click="close"
  >
    <image
      :src="currentImage"
      mode="widthFix"
      class="preview-image"
      :style="{ width: targetWidth + 'px' }"
    />
    <div
      class="save-style"
      @click.stop="saveImg"
    >保存相册</div>
  </view>
</template>

<script>
import sheep from '@/sheep';
export default {
  data () {
    return {
      visible: false,
      currentImage: '',
      targetWidth: 300 // 设定固定宽度
    };
  },
  methods: {
    open (url) {
      this.currentImage = url;
      this.visible = true;
    },
    close () {
      this.visible = false;
    },
    saveImg (url) {
      console.log('state.sign_img', this.currentImage)
      if (['WechatOfficialAccount', 'H5'].includes(sheep.$platform.name)) {
        sheep.$helper.toast('请长按图片保存');
        return;
      }
      uni.downloadFile({
        url: this.currentImage,
        success: (sres) => {
          console.log(sres);
          uni.saveImageToPhotosAlbum({
            filePath: sres.tempFilePath,
            success: (res) => {
              sheep.$helper.toast('保存成功');
            },
            fail: (err) => {
              sheep.$helper.toast('保存失败');
              console.log('图片保存失败:', err);
            },
          });
        }

      }).onProgressUpdate((res) => {
        uni.showLoading({
          title: '正在保存...'
        })
        if (res.progress == 100) {
          uni.hideLoading()
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.custom-preview {
  z-index: 999999;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
  .preview-image {
    position: absolute;
    top: 0;
  }
}
.save-style {
  position: fixed;
  bottom: 20rpx;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200rpx;
  height: 80rpx;
  border-radius: 50rpx;
  font-size: 32rpx;
  color: #fff;
  border: 2px solid linear-gradient(270deg, #003ad9 0%, #3dc8ff 100%);
  background: linear-gradient(270deg, #003ad9 0%, #3dc8ff 100%);
}
</style>